import store from './store'
import { getToken } from '@/utils/auth'

import {createRouter,RouterMount} from 'uni-simple-router';
const whiteList = ['/pages/home/index','/pagework/login/index','/pagework/healthy/foodGi']

const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routes: [...ROUTES]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
  if (getToken()) {
    /* has token*/
    if (to.path === '/pagework/login/index') {
      next({ path: '/pages/home/index' })
    } else {
      if (store.getters.name === '') {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          next({path: to.path, replace: true })
          // next({ ...to, replace: true })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            uni.$u.toast(err)
            next({ path: '/pagework/login/index' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/pagework/login/index`) // 否则全部重定向到登录页
    }
  }

})

// 全局路由后置守卫
router.afterEach((to, from) => {
  console.log('跳转结束->',from.path,to.path)
})


export {
	router,
	RouterMount
}
